package ${pPackage}.shiro.realm;

import ${pPackage}.common.exception.CommonException;
import ${pPackage}.pojo.User;
import ${pPackage}.service.impl.PermissionService;
import ${pPackage}.service.impl.UserService;
import ${pPackage}.vo.UserInfo;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.ArrayList;
/**
 * 自定义Realm,认证构造数据
 */
public class UserRealm extends AuthorizingRealm {

  public void setName(String name) {
    super.setName("UserRealm");
  }


  @Autowired
  UserService userService;
  @Autowired
  PermissionService permissionService;

  //认证方法
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    //获取用户的手机号和密码
    UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
    String mobile = upToken.getUsername();
    String password = new String(upToken.getPassword());
    User user = userService.findByMobile(mobile);
    //判断密码是否一致,是否启动
    if (user != null && user.getPassword().equals(password) && user.getState() == 1) {
      UserInfo userInfo = new UserInfo();
      try {
        Map<String, Object> menu = permissionService.getMenuByUserId(user.getId());
        List<String> apis = (List<String>) menu.get("apis");
        userInfo.setId(user.getId());
        userInfo.setMobile(user.getMobile());
        userInfo.setUsername(user.getUsername());
        userInfo.setPassword(user.getPassword());
        userInfo.setApis(apis);
      } catch (CommonException e) {
        // 假数据
        List<String> apis = new ArrayList<>();
        userInfo.setId(user.getId());
        userInfo.setMobile(user.getMobile());
        userInfo.setUsername(user.getUsername());
        userInfo.setPassword(user.getPassword());
        userInfo.setApis(apis);
        // return null;
      }
      //构造方法：安全数据，密码，realm域名
      SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userInfo, userInfo.getPassword(), this.getName());
      return info;
    }
    //返回null，会抛出异常，标识用户名和密码不匹配
    return null;
  }

  //授权方法
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    // 获取安全数据(API权限)
    UserInfo userInfo = (UserInfo) principalCollection.getPrimaryPrincipal();
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    for (String p : userInfo.getApis()) {
      // 添加权限
      info.addStringPermission(p);
    }
    return info;
  }
}

